//
//  GYAddressViewController.m
//  GoodLuck
//
//  Created by 郭为勇 on 2018/3/3.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYAddressViewController.h"
#import "GYNoAddressView.h"
#import "GYAddNewAddressViewController.h"
#import "GYAddressCell.h"
#import "GYNetWorkTools.h"
#import "GYRecriveAddress.h"

@interface GYAddressViewController ()<UITableViewDelegate,UITableViewDataSource>;

/** descrpition */
@property (nonatomic, weak) UITableView *tableView;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *addressList;

/** 没有收货地址视图 */
@property (nonatomic, strong) GYNoAddressView *noAddressView;
@end

@implementation GYAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化 (这里也要判断用户是否有地址 有则加载  没有则不加载)
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //加载用户地址
    [self loadUserReceiveAddress];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    //self.noAddressView.frame = self.view.bounds;
}

- (void)setupUI {
    self.navigationItem.title = @"地址管理";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"value_add" tagret:self action:@selector(addressBtuClick) button:nil];
    
    //初始化表格
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionFooterHeight = 10;
    tableView.sectionHeaderHeight = 0;
    
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
    
    //设置tableView的尾视图
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    footView.backgroundColor = [UIColor clearColor];
    UIButton *btu = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, ScreenWidth-40, 44)];
    btu.titleLabel.font = [UIFont systemFontOfSize:18];
    [btu setTitle:@"添加新地址" forState:UIControlStateNormal];
    [btu setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btu.layer.cornerRadius = 4;
    [btu setBackgroundColor:RGBColor(0, 158, 214)];//RGBColor(71, 163, 39)
    [btu addTarget:self action:@selector(addressBtuClick) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:btu];
    tableView.tableFooterView = footView;
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
}

- (void)setupNoAddressView {
    //1.首先要判断用户有没有地址  如果没有地址则加载没有地址的View  否则自然加载View
    GYNoAddressView *noAddressView = [[[NSBundle mainBundle] loadNibNamed:@"GYNoAddressView" owner:nil options:nil] firstObject];
    noAddressView.frame = self.view.bounds;
    __weak typeof(self) weakSelf = self;
    noAddressView.addNewAddressCallBack = ^{
        
        GYAddNewAddressViewController *newAddressVC = [[GYAddNewAddressViewController alloc] initWithNibName:@"GYAddNewAddressViewController" bundle:nil];
        //newAddressVC.orderAddress = NO;
        [weakSelf.navigationController pushViewController:newAddressVC animated:YES];
    };
    [self.view addSubview:noAddressView];
    
    self.noAddressView = noAddressView;
}


- (void)addressBtuClick {
    GYAddNewAddressViewController *newAddressVC = [[GYAddNewAddressViewController alloc] initWithNibName:@"GYAddNewAddressViewController" bundle:nil];
    newAddressVC.editState = NO;
    //newAddressVC.orderAddress = NO;
    [self.navigationController pushViewController:newAddressVC animated:YES];
}

- (void)loadUserReceiveAddress {
    
    [EasyLodingView showLodingText:@"加载中..."];
    [GYNetWorkTools requestUserAddress:^(NSDictionary *obj) {
        
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoding];
            NSArray *address_list = [datas objectForKey:@"address_list"];
            if (address_list.count == 0) {
                if (self.noAddressView == nil) {
                    //加载没有地址的视图
                    [self setupNoAddressView];
                }else {
                    self.noAddressView.hidden = NO;                    
                }
            }else {
                self.noAddressView.hidden = YES;
                self.addressList = [GYRecriveAddress loadUserRecriveAddress:address_list];
                [self.tableView reloadData];
            }
        }else if (code == 400) {
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            [EasyLodingView hidenLoding];
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"加载数据出错,请重新加载!"];
        [EasyLodingView hidenLoding];
        NSLog(@"loadUserAddress====%@",error);
    }];
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.addressList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GYAddressCell *cell = [GYAddressCell cellWithTableView:tableView];
    cell.address = self.addressList[indexPath.section];
    cell.currentRow = indexPath.section;
    __weak typeof(self) weakSelf = self;
    cell.btuClickBlock = ^(NSInteger tag,NSInteger currentRow) {
        switch (tag) {
            case 1:
            {
                GYAddNewAddressViewController *newAddressVC = [[GYAddNewAddressViewController alloc] initWithNibName:@"GYAddNewAddressViewController" bundle:nil];
                newAddressVC.editState = YES;
                //newAddressVC.orderAddress = NO;
                newAddressVC.model = weakSelf.addressList[indexPath.section];
                [self.navigationController pushViewController:newAddressVC animated:YES];
            }
                break;
                
            case 2:
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确认删除吗?" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sub = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    GYRecriveAddress *address = weakSelf.addressList[indexPath.section];
                    [GYNetWorkTools requestDeleteUserAddress:address.address_id success:^(NSDictionary *obj) {
                        int code = [[obj objectForKey:@"code"] intValue];
                        if (code == 200) {
                            [EasyTextView showSuccessText:@"删除地址成功!"];
                            [weakSelf.addressList removeObjectAtIndex:currentRow];
                            weakSelf.noAddressView.hidden = weakSelf.addressList.count == 0 ? NO : YES;
                            [tableView reloadData];
                        }else if (code == 400) {
                            [EasyTextView showText:@"删除地址失败!"];
                        }
                    } error:^(NSError *error) {
                        [EasyTextView showText:@"网络加载数据出错!"];
                        NSLog(@"deleteReceiveAddressFailed====%@",error);
                    }];

                }];
                
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:sub];
                [alertController addAction:cancel];
                
                [self presentViewController:alertController animated:YES completion:nil];
            }
                break;
                
            default:
                break;
        }
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYAddressCell *cell = [GYAddressCell cellWithTableView:tableView];
    
    return [cell cellHeight:self.addressList[indexPath.section]];
}

#pragma mark -- 懒加载

@end
